<?php

ini_set("memory_limit", "100M");
ini_set("max_execution_time", 36000);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/bean/HLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBteamsold.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBHLeague.class.php');

try {
	if ($_GET["pass"] != SCRIPT_PWD) die("Incorrect password");
	
	if (isset($_GET['date'])) {
		if (preg_match("/^[0-9]{4,4}[-][0-9]{2,2}[-][0-9]{2,2}$/", $_GET['date'])) {
			$date = strtotime($_GET['date']);
		}
		else die("Date must be of form YYYY-MM-DD");
	}
	else die("Date must be set!");	
	
	$dbcountry = new DBCountry();
	$dbdivision = new DBDivision();
	$dbteamsold = new DBteamsold();
	$dbleague = new DBLeague();
	$dbhleague = new DBHLeague();
	
	$countries = $dbcountry->getCountries();
	$hleagues = new ArrayObject();
	$numberNonExistingLeagues = 0;
	
	foreach ($countries as $country) {
		$divisions = $dbdivision->getDivisionsByCountry($country);
		
		foreach ($divisions as $division) {
			$leagues = $dbleague->getLeaguesByDivision($division);
			
			foreach ($leagues as $league) {
				$hleagueDB = $dbhleague->getHLeague($league->getLeagueID(), $date);
				if ($hleagueDB == null) {
					$hleague = new HLeague($league, $date);
					$teams = $dbteamsold->getTeamsByLeague($league, $date);
					if (count($teams) != 0) {
						
						if (count($teams) != 8) echo "League " . $league->getLeagueID() . " not complete. Only " . count($teams) . " teams in the database.<br />";
						foreach ($teams as $team) {
							if ($team->getUserID() == 0) {
								$hleague->setNumberBots($hleague->getNumberBots() + 1);
							}
							if ($team->isSupporter()) {
								$hleague->setNumberSupporters($hleague->getNumberSupporters() + 1);
							}
						}
						
						$hleagues->append($hleague);
						if (count($hleagues >= 100)) {
							$dbhleague->saveHLeagues($hleagues);
							$hleagues = new ArrayObject();
						}
					
					}
					else $numberNonExistingLeagues++;
				}
			}
			$dbhleague->saveHLeagues($hleagues);
			$hleagues = new ArrayObject();
		}
		echo $country->getName() . " finished successfully!<br />";
	}
	echo "All leagues converted!<br />";
	echo $numberNonExistingLeagues . " leagues didn't exist!";
}
catch (Exception $e) {
	echo $e->getMessage();
	print_r($e);
}

?>